package com.zym.init.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zym.init.core.exception.ServiceException;
import com.zym.init.mapper.RoleMapper;
import com.zym.init.mapper.UserMapper;
import com.zym.init.model.dto.PageDTO;
import com.zym.init.model.po.RolePo;
import com.zym.init.model.po.UserPo;
import com.zym.init.model.query.RoleQuery;
import com.zym.init.model.vo.RoleVo;
import com.zym.init.service.PermissionService;
import com.zym.init.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.zym.init.core.constant.CommonConstant.FORBIDDEN_OPERATION_ROLE_IDS;
import static com.zym.init.core.constant.CommonConstant.ONLY_ALLOW_MODIFY_PERMISSION_ROLE_IDS;

/**
 * @author zouyangming
 * @description 针对表【role(角色表)】的数据库操作Service实现
 * @createDate 2024-05-25 00:46:42
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RolePo>
        implements RoleService {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询权限列表
     */
    @Override
    public PageDTO<RoleVo> getPage(RoleQuery query) {
        // 分页查询
        Page<RolePo> page = lambdaQuery()
                .eq(query.getRoleId() != null, RolePo::getRoleId, query.getRoleId())
                .like(query.getRoleName() != null, RolePo::getRoleName, query.getRoleName())
                .eq(query.getRoleCode() != null, RolePo::getRoleCode, query.getRoleCode())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        // 封装返回
        return PageDTO.of(page, RolePo::toVo);
    }

    /**
     * 新增角色
     *
     * @return 结果
     */
    @Override
    public boolean add(RoleQuery query) {
        isRoleCodeExist(query.getRoleCode());
        RolePo role = new RolePo();
        role.setRoleName(query.getRoleName());
        role.setRoleCode(query.getRoleCode());
        role.setPermissionList(query.getPermissionList());
        role.setRoleDesc(query.getRoleDesc());
        role.setStatus(query.getStatus());
        return save(role);
    }

    /**
     * 编辑角色
     *
     * @return 结果
     */
    @Override
    public boolean edit(RoleQuery query) {
        if (Arrays.stream(FORBIDDEN_OPERATION_ROLE_IDS).toList().contains(query.getRoleId())) {
            throw new ServiceException("禁止操作系统角色");
        }
        QueryWrapper<RolePo> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", query.getRoleId());
        RolePo po = getOne(wrapper);
        if (po == null) {
            throw new ServiceException("角色不存在");
        }
        if (!po.getRoleCode().equals(query.getRoleCode())) {
            isRoleCodeExist(query.getRoleCode());
        }
        RolePo role = new RolePo();
        role.setRoleId(query.getRoleId());
        if (Arrays.stream(ONLY_ALLOW_MODIFY_PERMISSION_ROLE_IDS).toList().contains(query.getRoleId())) {
            role.setPermissionList(query.getPermissionList());
        } else {
            role.setRoleName(query.getRoleName());
            role.setPermissionList(query.getPermissionList());
            role.setRoleDesc(query.getRoleDesc());
            role.setStatus(query.getStatus());
        }
        return updateById(role);
    }

    /**
     * 判断权限代码是否存在
     */
    private void isRoleCodeExist(String code) {
        QueryWrapper<RolePo> wrapper = new QueryWrapper<>();
        wrapper.eq("role_code", code);
        if (count(wrapper) > 0) {
            throw new ServiceException("角色代码已存在");
        }
    }

    /**
     * 根据角色代码获取角色信息列表
     *
     * @param codes 角色代码列表
     * @return 角色信息列表
     */
    @Override
    public List<RoleVo> getByCodeList(List<String> codes) {
        List<RoleVo> list = new ArrayList<>();
        if (codes != null && !codes.isEmpty()) {
            List<RolePo> pos = lambdaQuery()
                    .in(RolePo::getRoleCode, codes)
                    .list();
            for (RolePo po : pos) {
                list.add(po.toVo());
            }
        }
        return list;
    }

    /**
     * 判断角色代码是否被使用
     *
     * @param ids 角色ID列表
     * @return 是否被使用
     */
    @Override
    public boolean isRoleCodeUsed(List<Long> ids) {
        QueryWrapper<RolePo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id", ids);
        List<RolePo> pos = list(queryWrapper);
        List<String> codeList = new ArrayList<>();
        for (RolePo po : pos) {
            codeList.add(po.getRoleCode());
        }
        return isCodeUsed(codeList);
    }

    /**
     * 判断角色代码是否被使用
     *
     * @param roleCodeList 权限代码列表
     * @return 是否被使用
     */
    public boolean isCodeUsed(List<String> roleCodeList) {
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        for (String s : roleCodeList) {
            queryWrapper.apply("JSON_CONTAINS(role_list, '\"" + s + "\"')");
        }
        return userMapper.selectCount(queryWrapper) > 0;
    }

}




